﻿using System;
using System.IO;
using Gumini.JulaDB.Provider;
using Gumini.JulaDB.Test.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Gumini.JulaDB.Test
{
    /// <summary>
    /// Test for loading and saving a database to a file.
    /// </summary>
    [TestClass]
    public class FileDatabaseTest
    {
        private const string DatabasePath = "test.juladb";

        private static void CheckFileExists(bool isEmpty)
        {
            var fileInfo = new FileInfo(DatabasePath);
            Assert.IsTrue(fileInfo.Exists);
            Assert.IsTrue(isEmpty ? fileInfo.Length == 0 : fileInfo.Length > 0);
        }

        /// <summary>
        /// Creates a database, saves it to a file and then loads it again.
        /// NOTE: this test requires write access to the current test directory, otherwise it will fail.
        /// </summary>
        [TestMethod]
        public void CreateNewFileDatabase()
        {
            // ensure that the file doesn't exist already
            if (File.Exists(DatabasePath))
                File.Delete(DatabasePath);

            PersonTestDataCreator personData;

            // creating a new database
            using (var connection = new JulaDbConnection(String.Format("Data Source={0}", DatabasePath)))
            {
                connection.Open();

                // file should be created, but empty
                CheckFileExists(isEmpty: true);

                personData = new PersonTestDataCreator(connection);
            }
            // data should be saved on Dispose

            // file should be nonempty
            CheckFileExists(isEmpty: false);

            // opening the file database
            using (var connection = new JulaDbConnection(String.Format("Data Source={0}", DatabasePath)))
            {
                connection.Open();

                CheckFileExists(isEmpty: false);

                // issuing a simple query
                connection.ExecuteValidScalar("select count(*) from Person", personData.TotalPersonCount);
            }
        }
    }
}
